﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using Inovout.Component;
using Inovout.Data.Service;
using Inovout.Membership.Security.OAuth.AuthorizationServer.Mail;
using Inovout.Membership.Security.OAuth.AuthorizationServer.XMail263Service.XmapiImplService;
using Inovout.People.Domain;

namespace Inovout.Membership.Security.OAuth.AuthorizationServer
{
    public class XMail263CredentialProvider : MailCredentialProvider
    {
        private readonly string key;
        private readonly string domain;
        private readonly string account;
        private IRepositoryService<MailCredential> mailCredentialService;
        private XmapiImplService xmapiImplService;
        public XMail263CredentialProvider()
        {
            key = "uieHDj93Wx";
            domain = "samples.cn";
            account = "samples.cn";
            mailCredentialService = ComponentRegistry.Resolve<IRepositoryService<MailCredential>>();
            xmapiImplService = new XmapiImplService();

        }
        public MailCredential Validate(IMailAuthenticationCredential credentiaInfo)
        {
            if (!Authenticate(credentiaInfo.Mail, credentiaInfo.Password))
            {
                return null;
            }
            MailCredential mailCredential = mailCredentialService.Query()
                    .SingleOrDefault(a => a.Mail == credentiaInfo.Mail) ?? new MailCredential(credentiaInfo.Mail);

            return mailCredential;
        }
        private bool Authenticate(string userName, string password)
        {
            //在引用WebService生成的代码的Reference.cs文件中将“http://macom.263.net/axis/xmapi”替换为"http://xmapi.webservices.ma.net263.com"
            //一定要注意不能整个解决方案中替换，一定要在当前文件中替换

            //如果用户邮箱帐号输全，则替换掉，只保留帐号
            userName = userName.Trim().Replace("@samples.cn", string.Empty);
            string sign = Md5Sign(userName + domain + password + key);
            //263验证登录，返回0成功，其他失败
            int result = xmapiImplService.authentication_New(userName, domain, password, 0, account, sign);
            return result == 0;

        }
        private UserInfo GetUserInfo(string mail)
        {
            string userName = mail.Trim().Replace("@samples.cn", string.Empty);

            string sign = Md5Sign(userName + domain + account + key);
            string userXml = xmapiImplService.getUserInfo_New(userName, domain, account, sign);
            UserInfo user = null;
            if (!string.IsNullOrEmpty(userXml))
            {
                user = new UserInfo();
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(userXml);

                XmlNode userNode = xmlDocument.SelectSingleNode("user");
                user.Userid = userNode["userid"].InnerText;
                user.Name = userNode["name"].InnerText;
                user.Departmentid = userNode["departmentid"].InnerText;
                user.Office = userNode["office"].InnerText;
                user.Mobile = userNode["mobile"].InnerText;
                user.Phone = userNode["phone"].InnerText;
                user.Fax = userNode["fax"].InnerText;
            }

            return user;
        }
        public Person GetPerson(string mail)
        {
            UserInfo userInfo = GetUserInfo(mail);
            Person person = new Person();
            person.Name = userInfo.Name.Trim();
            person.Contacts.Add(new Contact(ContactMethod.Mobile, userInfo.Mobile));
            person.Contacts.Add(new Contact(ContactMethod.EMail, userInfo.Userid));

            return person;

        }
        private string Md5Sign(string value)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buffer = Encoding.Default.GetBytes(value);
            string result = BitConverter.ToString(md5.ComputeHash(buffer));
            return result.Replace("-", "").ToLower();

        }

    }
}
